from flask import Flask
from flask import jsonify
from flask import json
from flask import request
from subprocess import Popen
from subprocess import call

app = Flask(__name__)


class StreamPlayer:

  def connect(self, url):
    try:
      self.process = Popen(['ogg123', url])
      return True
    except Exception, e:
      print "Error while trying to connect ogg123:", e
      return False

  def disconnect(self):
    self.process.terminate()
    return_code = self.process.poll()
    if return_code == 0:
      return True
    else:
      return False


player = StreamPlayer()

@app.route('/connect', methods = ['POST'])
def connect_to_stream():
  status_code = check_content_type(request)
  if status_code == 200:
    try:
      data = json.loads(request.data)
      url = data['url']
      print "Trying to connect to", url
      player.connect(url)
    except Exception, e:
      print "Error while trying to connect ogg123:", e
      status_code = 404
  return create_response(status_code)

@app.route('/disconnect')
def disconnect_from_stream():
  success = player.disconnect()
  if success:
   status_code = 200
  else:
   status_code = 400
  return create_response(status_code)

@app.route('/volume', methods = ['POST'])
def set_volume():
  status_code = check_content_type()
  if status_code == 200:
    data = json.loads(request.data)
    try:
      volume =  data['volume']
      return_code = call(['amixer','set','PCM',"{}%".format(volume)])
      if return_code == 0:
        status_code = 200
      else:
        status_code = 415
    except Exception, e:
      print e
      status_code = 415
  return create_response(status_code)

def create_response(status_code):
  if status_code == 200:
    resp = jsonify({'response':'ok'})
  else:
    resp = jsonify({'response':'error'})
  resp.status_code = status_code
  return resp

def check_content_type():
  if request.headers['Content-Type'] == 'application/json':
    return 200
  else:
    return 415

if __name__ == '__main__':
    app.run(host = '0.0.0.0')

